package com.helmlabs.grouper.cms.webapp.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.helmlabs.grouper.cms.dao.PageDao;
import com.helmlabs.grouper.cms.model.AbstractModule;
import com.helmlabs.grouper.cms.model.Page;
import com.helmlabs.grouper.cms.model.StaticContentModule;
import com.helmlabs.grouper.cms.view.FreemarkerView;

public class DispatcherServlet extends HttpServlet {

	private PageDao pageDao;
	private Log log = LogFactory.getLog(getClass());
	
	public void init(ServletConfig config){
		log.debug("starting up the grouper dispatcher servlet");
		pageDao = (PageDao)WebApplicationContextUtils.getWebApplicationContext(config.getServletContext()).getBean("pageDao");
		log.debug("set the page dao in the grouper dispatcher servlet");
	}
	
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    	throws ServletException, IOException {
    	doPost(req, resp);
    }
    
    /**
     * perform all the work necessary to render the page requested.
     * if the page id is not set in the request uri, then ignore the request
     * and keep moving. 
     * 
     */
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
    	throws ServletException, IOException {
    	log.debug("processing the request through grouper dispatcher for the request " + req);
    	PrintWriter out = resp.getWriter();
    	
    	String[] requesturi = req.getRequestURI().split("/");
    	if (requesturi.length>2){
    		Page page = pageDao.get(new Long(findPageId(req.getRequestURI())));
    		Map map = new HashMap();
    		map.putAll(req.getParameterMap());
    		out.println((new FreemarkerView()).render(page, map));
    	}
    	else {
    		AbstractModule module = new StaticContentModule();
    		out.println(module.displayAdminForm(req, resp));
    	}
    }
    
    /**
     * Find the page ID from the request URI. This method looks
     * through the request uri for the page/ and will provide the 
     * string that follows the page/ portion of the request URI
     * 
     * @param requestURI
     * @return String id of the page requested
     */
    private String findPageId(String requestURI){
    	String[] split = requestURI.split("/");
    	if (split!=null && split.length>0){
    		for (int i=0; i<split.length; i++){
    			if ("page".equals(split[i]) && (i+1)<split.length){
    				return split[i+1];
    			}
    		}
    	}
    	return null;
    }

	
	

}
